package com.sc.gateway.core.filter;


import com.sc.common.properties.WhiteListProperties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 任何请求spring cloud家族的任何子系统，首先需要通过这一层的过滤器。
 * 此过滤器需要做如下方面的工作：
 * 1.如果是登录操作，则调用sso服务登录，sso服务登录成功后返回token给前端；
 * 2.如果是非登录操作，则从请求中获取token参数，根据token调用sso服务判断是否是有效的请求（判定有效请求有很多工作要做，比如检验是否是合法登录用户，是否有权限访问系统资源等）
 * Created by wust on 2019/3/13.
 */
@Component
public class AccessFilter implements GlobalFilter {
    static Logger logger = LogManager.getLogger(AccessFilter.class);

    @Autowired
    private AccessFilterForWeb accessFilterForWeb;

    @Autowired
    private AccessFilterForApi accessFilterForApi;

    @Autowired
    private AccessFilterForApp accessFilterForApp;

    @Autowired
    private WhiteListProperties whiteListProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain gatewayFilterChain) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        ServerHttpResponse response = serverWebExchange.getResponse();

        logger.info("网关拦截日志，请求URL={}，请求URI={},请求参数={}",request.getPath().toString(),request.getURI().toString(),request.getQueryParams());

        String reqUrl = request.getPath().toString();

        /**
         * 未登录，允许通过的请求名单
         */
        String[] whiteList = whiteListProperties.getNoLogin();
        if(whiteList != null && whiteList.length > 0){
            for (String s : whiteList) {
                if(s.equals(reqUrl)) {
                    response.setStatusCode(HttpStatus.OK);
                    return gatewayFilterChain.filter(serverWebExchange);
                }
            }
        }

        if(reqUrl.contains("/web/")){
            return accessFilterForWeb.filter(serverWebExchange,gatewayFilterChain);
        }else if(reqUrl.contains("/app/")){
            return accessFilterForApp.filter(serverWebExchange,gatewayFilterChain);
        }else if(reqUrl.contains("/api/open/")){
            return accessFilterForApi.filter(serverWebExchange,gatewayFilterChain);
        }else{
            logger.error("非法的请求，reqUrl={}",reqUrl);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
}
